<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;

class ShareController extends Controller{
    public function run(Request $request){
        $param = $request->all();
        $link = urldecode($param['url']);
        $appid = 'wx8bce72636ba79f5e';
        $secret = 'c98e8c75b8a31765e6745b8cc24a4180';

        $newlink = explode('#',$link);
        $url = $newlink[0];

        // 获取access_token
        $accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        //请求地址获取access_token
        $accessTokenJson = file_get_contents($accessTokenUrl);
        $accessTokenObj = json_decode($accessTokenJson,1);
        $access_token = $accessTokenObj['access_token'];

        // 根据access_token获取jsapiticket
        $ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";
        $ticketJson = file_get_contents($ticketUrl);
        $ticketJson = json_decode($ticketJson,1);
        $jsapiTicket = $ticketJson['ticket'];

        // 随机生成16位字符串
//        $strs="QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm";
//        $noncestr = substr(str_shuffle($strs),mt_rand(0,strlen($strs)-11),16);

        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $noncestr = "";
        for ($i = 0; $i < 16; $i++) {
            $noncestr .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }

        //时间戳
        $time = time();
        $params = array(
            'noncestr'=>$noncestr,
            'jsapi_ticket'=>$jsapiTicket,
            'timestamp'=>time(),
            'url'=>$url
        );
        ksort($params);
        $jsapiTicketNew = urldecode(http_build_query($params));

        //对string1作sha1加密
        $signature = sha1($jsapiTicketNew);
        //存入数据
        $data = [
            'appid' => $appid,
            'timestamp' => $time,
            'nonceStr' => $noncestr,
            'signature' => $signature,
            'jsapiTicket' => $jsapiTicket,
            'url' => $link,
            'jsApiList'=>[
                'previewImage',
                'hideAllNonBaseMenuItem',
                'showMenuItems',
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareTimelineData',
                'onMenuShareAppMessageData',
                'chooseWXPay'
            ],
            "rawString" => $jsapiTicketNew
        ];

        return response()->json($data);
    }
}